package com.ebook.eboo.Controller;

import com.ebook.eboo.Service.bookService;
import com.ebook.eboo.pojo.Book;
import com.ebook.eboo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
public class BookConteoller {

    Book book = new Book();

    @Autowired
    bookService bookService;

    @CrossOrigin
    @PostMapping(value = "api/covers")
    @ResponseBody
    public String coversUpload(MultipartFile file) throws Exception{
        String folder = "E:/idea/images";
        File imageFolder = new File(folder);
        File f = new File(imageFolder,file.getOriginalFilename());
        try{
            file.transferTo(f);
            String imageURL = "http://localhost:8443/api/file/" + f.getName();
            System.out.println(imageURL);
            book.setCover(imageURL);
            return imageURL;
        }catch (IOException e){
            e.printStackTrace();
            return "";
        }
    }

    @CrossOrigin
    @PostMapping(value = "api/source")
    @ResponseBody
    public String txtUpload(MultipartFile file) throws Exception{
        String folder = "E:/idea/images";
        File txtFolder = new File(folder);
        File f = new File(txtFolder,file.getOriginalFilename());
        try{
            file.transferTo(f);
            String imageURL = "http://localhost:8443/api/file/" + f.getName();
            System.out.println(imageURL);
            book.setResource(imageURL);
            return imageURL;
        }catch (IOException e){
            e.printStackTrace();
            return "";
        }
    }
    @CrossOrigin
    @PostMapping(value = "api/save_book")
    @ResponseBody
    public Book save_book(@RequestBody Book book_){
        return bookService.save(book_);
    }

}
